//
//  HttpMethod.m
//  AgriMobile
//
//  Created by 春名 啓作 on 11/05/13.
//  Copyright 2011 （株）アグリコミュニケーションズ. All rights reserved.
//

#import "HttpMethod.h"


@implementation HttpMethod

NSData *buffer;

- (NSString *)doGet:(NSString *) urlstr {

	NSURL *url = [NSURL URLWithString:urlstr];
	NSURLRequest *request = [NSURLRequest requestWithURL:url];
	NSURLResponse *response = nil;
	NSError *error = nil;

	NSData *data = [
					NSURLConnection
					sendSynchronousRequest : request
					returningResponse : &response
					error : &error
					];
	
	// error
	NSString *error_str = [error localizedDescription];
	if (0<[error_str length]) {
		UIAlertView *alert = [
							  [UIAlertView alloc]
							  initWithTitle : @"RequestError"
							  message : error_str
							  delegate : nil
							  cancelButtonTitle : @"OK"
							  otherButtonTitles : nil
							  ];
		[alert show];
		[alert release];
		return @"";
	}
	
	// response
	int enc_arr[] = {
		NSUTF8StringEncoding,			// UTF-8
		NSShiftJISStringEncoding,		// Shift_JIS
		NSJapaneseEUCStringEncoding,	// EUC-JP
		NSISO2022JPStringEncoding,		// JIS
		NSUnicodeStringEncoding,		// Unicode
		NSASCIIStringEncoding			// ASCII
	};
	NSString *data_str = nil;
	int max = sizeof(enc_arr) / sizeof(enc_arr[0]);
	for (int i=0; i<max; i++) {
		data_str = [
					[NSString alloc]
					initWithData : data
					encoding : enc_arr[i]
					];
		if (data_str!=nil) {
			break;
		}
	}
	
	//No logging
	//NSLog(@"data_str = %@", data_str);
	return data_str;
}

- (NSString *)doPost:(NSString *)action parameters:(NSDictionary *)param {

    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@%@",URLRoot,action]];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
	NSMutableData* paramData = [[NSMutableData alloc] init];

	//NSString *paramName;
	NSString *lead = @"";
	int paramCount = 0;
	//while (paramName = (NSString*)[paramEnum nextObject]) {
	for(NSString* paramName in [param allKeys]){
		if (paramCount > 0) {
			lead = @"&";
		}

		[paramData appendData:[[NSString stringWithFormat:@"%@%@=%@",
							   lead,paramName,[param objectForKey:paramName]]
						dataUsingEncoding:NSUTF8StringEncoding]];

		NSLog(@"param[%02d]%@%@=%@", paramCount,lead,paramName,[param objectForKey:paramName]);
		paramCount++;
	}
    [request setHTTPMethod:@"POST"];
    //[request setValue:header forHTTPHeaderField:@"Authorization"];
    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    [request setHTTPBody:paramData];

    NSURLResponse *response = nil;
    NSError       *error    = nil;
    [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
	
	/*
    NSURLConnection *conn = [NSURLConnection connectionWithRequest:request delegate:self];
    if (conn) {
        buffer = [[NSMutableData data] retain];
    } else {
        // error handling
		NSLog(@"Error");
    }
	 */
	return @"";
}

- (void)connection:(NSURLConnection *)conn didReceiveResponse:(NSURLResponse *)res {
	 
    NSHTTPURLResponse *hres = (NSHTTPURLResponse *)res;
    NSLog(@"Received Response. Status Code: %d", [hres statusCode]);
    NSLog(@"Expected ContentLength: %qi", [hres expectedContentLength]);
    NSLog(@"MIMEType: %@", [hres MIMEType]);
    NSLog(@"Suggested File Name: %@", [hres suggestedFilename]);
    NSLog(@"Text Encoding Name: %@", [hres textEncodingName]);
    NSLog(@"URL: %@", [hres URL]);
    NSLog(@"Received Response. Status Code: %d", [hres statusCode]);
    NSDictionary *dict = [hres allHeaderFields];
    NSArray *keys = [dict allKeys];
    for (int i = 0; i < [keys count]; i++) {
        NSLog(@"    %@: %@",
              [keys objectAtIndex:i],
              [dict objectForKey:[keys objectAtIndex:i]]);
    }
    [buffer setLength:0];
}


- (void)connection:(NSURLConnection *)conn didReceiveData:(NSData *)receivedData {
    [buffer appendData:receivedData];
}


- (void)connection:(NSURLConnection *)conn didFailWithError:(NSError *)error {
    [conn release];
    [buffer release];
    NSLog(@"Connection failed: %@ %@", [error localizedDescription], [[error userInfo] objectForKey:NSErrorFailingURLStringKey]);
}


- (void)connectionDidFinishLoading:(NSURLConnection *)conn {
    NSLog(@"Succeed!! Received %d bytes of data", [buffer length]);
    NSString *contents = [[NSString alloc] initWithData:buffer encoding:NSUTF8StringEncoding];
    NSLog(@"%@", contents);
    [buffer release];
}

/*
 NSMutableArray* anArray = [NSMutableArray array];
 NSEnumerator *enumerator = [posts objectEnumerator];
 NSArray *post;
 NSMutableDictionary *postsInSections = [[NSMutableDictionary alloc] init];
 while (post = (NSArray*)[enumerator nextObject]) {
 NSLog(@"%@, %@, %@", [post objectAtIndex:1], [post objectAtIndex:3], [post objectAtIndex:4]);
 //[anArray addObject: [item objectForKey:@"title"]];
 //[anArray addObject: [post objectAtIndex:3]];
 NSMutableString *postDate = [NSMutableString stringWithString:[post objectAtIndex:1]];
 int replaced = [postDate replaceOccurrencesOfString:@"月"
 withString:@"/"
 options:0
 range:NSMakeRange(0, [postDate length])];
 replaced = [postDate replaceOccurrencesOfString:@"日"
 withString:@""
 options:0
 range:NSMakeRange(0, [postDate length])];
 
 if ([postsInSections objectForKey:[post objectAtIndex:0]] == nil) {
 anArray = [NSMutableArray array];
 [postsInSections setObject:anArray forKey:[post objectAtIndex:0]];
 }
 anArray = [postsInSections objectForKey:[post objectAtIndex:0]];
 
 [anArray addObject: [NSString stringWithFormat:@"%@ %@ %@",
 postDate,[post objectAtIndex:3],[post objectAtIndex:4]]];
 }
 self.postsInSection = [NSDictionary dictionaryWithDictionary:postsInSections];
 
 */
@end
